<template>
  <view class="publish-container">
    <!-- 文字编辑区域 -->
    <view class="content-editor">
      <textarea
        v-model="content"
        placeholder="分享你的想法..."
        :maxlength="1000"
        class="content-textarea"
        @input="handleInput"
      ></textarea>
      <view class="word-count">{{ content.length }}/1000</view>
    </view>

    <!-- 话题展示区域 -->
    <view class="topics-container" v-if="topics.length > 0">
      <view class="topic-item" v-for="(topic, index) in topics" :key="index">
        #{{ topic }}
      </view>
    </view>

    <!-- 图片上传区域 -->
    <view class="upload-section">
      <view class="image-list">
        <view 
          class="image-item" 
          v-for="(image, index) in images" 
          :key="index"
        >
          <image :src="image" mode="aspectFill"></image>
          <view class="delete-btn" @click.stop="deleteImage(index)">×</view>
        </view>
        <view class="upload-btn" @click="chooseImage" v-if="images.length < 9">
          <uni-icons type="camera" size="30" color="#999"></uni-icons>
          <text>添加图片</text>
        </view>
      </view>
    </view>

    <!-- 位置选择区域 -->
    <view class="location-section" @click="chooseLocation">
      <uni-icons type="location" size="20" color="#666"></uni-icons>
      <text class="location-text">{{ location || '添加位置' }}</text>
    </view>

    <!-- 底部发布按钮 -->
    <view class="bottom-bar">
      <button 
        class="publish-btn" 
        :disabled="!content.trim()"
        @click="handlePublish"
      >
        发布
      </button>
    </view>
  </view>
</template>

<script>
import { request, uploadFile } from '@/utiles/request'

export default {
  data() {
    return {
      content: '',
      images: [],
      location: '',
      topics: [],
      uploading: false,
      user_id: 1 // 这里应该从用户状态或缓存中获取
    }
  },
  methods: {
    handleInput(e) {
      this.content = e.detail.value
      // 提取话题
      const topicRegex = /#([^#\s,.，。！？!?]+)/g
      const matches = this.content.match(topicRegex)
      this.topics = matches ? matches.map(t => t.slice(1)) : []
    },
    async chooseImage() {
      try {
        const res = await uni.chooseImage({
          count: 9 - this.images.length,
          sizeType: ['original', 'compressed'],
          sourceType: ['album', 'camera']
        })
        
        this.uploading = true
        uni.showLoading({
          title: '上传中...'
        })

        // 构建FormData
        const formData = new FormData()
        res.tempFilePaths.forEach((filePath, index) => {
          formData.append('images', {
            uri: filePath,
            type: 'image/jpeg',
            name: `image${index}.jpg`
          })
        })

        // 上传图片
        const uploadRes = await uploadFile({
          url: '/admin/upload/images',
          filePath: res.tempFilePaths[0], // 使用第一张图片作为主文件
          name: 'images',
          formData: formData
        })
		
        const data = JSON.parse(uploadRes.data)
		console.log(data)
        if (data.code === 0) {
          // 处理返回的图片URL
          const newImages = Array.isArray(data.data) ? data.data : [data.data]
          this.images = [...this.images, ...newImages]
		  
        } else {
          throw new Error(data.message || '上传失败')
        }
      } catch (error) {
        uni.showToast({
          title: error.message || '上传失败',
          icon: 'none'
        })
      } finally {
        this.uploading = false
        uni.hideLoading()
      }
    },
    deleteImage(index) {
      this.images.splice(index, 1)
    },
    async chooseLocation() {
      try {
        const res = await uni.chooseLocation()
        this.location = res.name
      } catch (error) {
        if (error.errMsg !== 'chooseLocation:fail cancel') {
          uni.showToast({
            title: '获取位置失败',
            icon: 'none'
          })
        }
      }
    },
    async handlePublish() {
      if (!this.content.trim()) {
        uni.showToast({
          title: '请输入内容',
          icon: 'none'
        })
        return
      }

      if (this.uploading) {
        uni.showToast({
          title: '图片上传中，请稍候',
          icon: 'none'
        })
        return
      }

      uni.showLoading({
        title: '发布中...'
      })

      try {
        const res = await request({
          url: '/admin/api/community/posts',
          method: 'POST',
          data: {
            user_id: this.user_id,
            content: this.content,
            images: this.images,
            location: this.location
          }
        })

        if (res.data.code === 200) {
          uni.showToast({
            title: '发布成功',
            icon: 'success'
          })
          
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          uni.showToast({
            title: res.data.message || '发布失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    }
  }
}
</script>

<style>
.publish-container {
  min-height: 100vh;
  background-color: #ffffff;
  padding: 30rpx;
  padding-bottom: 120rpx;
}

.content-editor {
  position: relative;
  margin-bottom: 30rpx;
}

.content-textarea {
  width: 100%;
  height: 300rpx;
  font-size: 30rpx;
  line-height: 1.6;
  padding: 20rpx;
  box-sizing: border-box;
}

.word-count {
  position: absolute;
  right: 20rpx;
  bottom: 20rpx;
  font-size: 24rpx;
  color: #999;
}

.topics-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.topic-item {
  background-color: #e6f3ff;
  color: #1890ff;
  padding: 10rpx 20rpx;
  border-radius: 30rpx;
  font-size: 26rpx;
}

.upload-section {
  margin-bottom: 30rpx;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.image-item {
  width: 200rpx;
  height: 200rpx;
  position: relative;
}

.image-item image {
  width: 100%;
  height: 100%;
  border-radius: 12rpx;
}

.delete-btn {
  position: absolute;
  top: -20rpx;
  right: -20rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: rgba(0, 0, 0, 0.5);
  color: #ffffff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
}

.upload-btn {
  width: 200rpx;
  height: 200rpx;
  background-color: #f5f7fa;
  border-radius: 12rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 26rpx;
}

.upload-btn text {
  margin-top: 10rpx;
}

.location-section {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-top: 1rpx solid #f5f5f5;
}

.location-text {
  margin-left: 10rpx;
  font-size: 28rpx;
  color: #666;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  padding: 20rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.publish-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #4CAF50;
  color: #ffffff;
  border-radius: 40rpx;
  font-size: 30rpx;
}

.publish-btn[disabled] {
  background-color: #cccccc;
  color: #ffffff;
}
</style>